package main

import (
	"io"
	"net/http"
	"os"
	"strings"
)

/**
1、修改index.html文件（忽略这步操作）
window.location.pathname = '/projects/editor/';

2、修改js/projects.bundle.js文件
# 将 https://cdn.assets.scratch.mit.edu 替换为 http://127.0.0.1:8000（即替换为ip或域名）
sed -i 's/https:\/\/cdn.assets.scratch.mit.edu/http:\/\/127.0.0.1:8000/g' js/projects.bundle.js

# 将 https://assets.scratch.mit.edu 替换为 http://127.0.0.1:8000（即替换为ip或域名）
sed -i 's/https:\/\/assets.scratch.mit.edu/http:\/\/127.0.0.1:8000/g' js/projects.bundle.js
*/

func main() {
	// http.Handle("/", http.FileServer(http.Dir("."))) // 文件服务器
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		p := r.URL.Path
		// fmt.Println(p)
		filename := strings.Trim(p, "/")
		if strings.HasPrefix(p, "/internalapi/asset") && (strings.HasSuffix(p, "/get/") || strings.HasSuffix(p, "/get")) {
			filename = strings.Trim(strings.TrimRight(filename, "get"), "/")
			p = filename
		}

		typ := "text/html"
		if p == "/" {
			filename = "index.html"
		} else if p == "/projects/editor/" || p == "/projects/editor" {
			filename += "/index.html"
		} else if p == "/session/" || p == "/session" {
			typ = "application/json"
		} else if strings.HasSuffix(p, ".ico") {
			typ = "image/x-icon"
		} else if strings.HasSuffix(p, ".js") {
			typ = "application/javascript"
		} else if strings.HasSuffix(p, ".css") {
			typ = "text/css"
		} else if strings.HasSuffix(p, ".svg") {
			typ = "image/svg+xml"
		} else if strings.HasSuffix(p, ".wav") {
			typ = "audio/x-wav"
		} else if strings.HasSuffix(p, ".png") {
			typ = "image/png"
		} else if strings.HasSuffix(p, ".jpg") {
			typ = "image/jpeg"
		}
		w.Header().Add("Content-Type", typ)

		f, err := os.Open(filename)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			w.Write(nil)
			return
		}
		b, _ := io.ReadAll(f)
		w.Write(b)
	})

	http.ListenAndServe(":8000", nil)
}
